package com.example.calculate;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.TextView;

public class CalculateActivity extends ActionBarActivity {

	TextView contentShow;
	
	String content = new String();
	
	private PopMenu popMenu;
	
	List<String> recordList;
	
	String fileName = "record.txt";
	
	boolean inputInit = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calculate);

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
		
		
		contentShow = (TextView)findViewById(R.id.content);
		
		
		try {
			recordList = this.readRecordFromFile(fileName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			recordList = new ArrayList<String>();
		}
		popMenu = new PopMenu(this);
		//popMenu.addItems(new String[] { "ͣ1", "2", "3", "4", "5" });		
		popMenu.addItems(recordList.toArray(new String[recordList.size()]));
		popMenu.setOnItemClickListener(popmenuItemClickListener);
		
		Button button1 = (Button) findViewById(R.id.button1);
		button1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				popMenu.showAsDropDown(v);
			}
		});
		
	}

	OnItemClickListener popmenuItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			
			String str = popMenu.getSelectStr(position);
			historyResult(str.split("=")[1]);
			popMenu.dismiss();
		}
	};
	
	
	public void historyResult(String number){
		String lastStr = getLastStr();
		if(effect('1',lastStr!=null?lastStr.charAt(0):null)){
			String content = this.getContent()+number;
			this.setContent(content);
			showText();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.calculate, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_calculate,
					container, false);
			return rootView;
		}
	}
	
	private void initInput(){
		if(inputInit){
			this.content = new String();
			inputInit = false;
		}
	}
	public void clickCalcuButtonHander(View view){
		initInput();
    	Button b = (Button)view;
		String name = (String)b.getText();
		//System.err.println(name);
		
		String lastStr = getLastStr();
		if(effect(name.charAt(0),lastStr!=null?lastStr.charAt(0):null)){
			String content = this.getContent()+name;
			this.setContent(content);
			showText();
		}
		
		
    }
	public boolean effect(Character inputStr,Character lastStr){
		
		if(lastStr==null){
			if(inputStr=='('||Calucate.isNumber(inputStr)){
				return true;
			}
		}else{
			if(Calucate.isNumber(inputStr)){
				if(Calucate.isNumber(lastStr)||Calucate.isSignCalu(lastStr)||lastStr=='('){
					return true;
				}
			}else{
				if(inputStr==')'){
					if(Calucate.isNumber(lastStr)||lastStr==')'){
						return true;
					}
				}else if(inputStr=='('){
					if(Calucate.isSignCalu(lastStr)||lastStr=='('){
						return true;
					}
				}else{
					if(Calucate.isNumber(lastStr)||lastStr==')'){
						return true;
					}
				}
				
			}
			
		}
		return false;
		
	}
	
	public boolean isNumberStr(char str){
		return Calucate.isNumber(str);
	}
	public String getLastStr(){
		int lenght = this.content.length();
		
		if(lenght==0){
			return null;
		}
		String lastStr = this.content.substring(lenght-1);
		return lastStr;
	}
    
    public void clickSpecialButtonHander(View view) {
    	//System.out.println("b");
    	initInput();
    	if(view.getId()==R.id.button_Backspace){
    		if(content!=null&&content.length()>0){
    			String content = this.getContent().substring(0, this.getContent().length()-1);
    			this.setContent(content);
    		}
		}else if(view.getId()==R.id.button_C){
			this.setContent(new String());
		}else if(view.getId()==R.id.button_calcute){
			String content = this.getContent();
			try {
				Double d = Calucate.recursiveCalStr(content);
				this.recordList.add(content+"="+d);
				popMenu.addItem(content+"="+d);
				this.setContent(d.toString());
				inputInit = true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    	showText();
		
	}
    public void showText(){
    	contentShow.setText(content);  
    	contentShow.invalidate(); 
    }
    
    
    public void writeFile(String fileName,String writestr) throws IOException{
		
    	FileOutputStream fileOut = this.openFileOutput(fileName, this.MODE_APPEND);
    	
    	byte[] buffer = writestr.getBytes("UTF-8");
    	
    	fileOut.write(buffer);
    	
    	fileOut.close();
    	
	}
    
    public void writeRecord2File(String fileName,List<String> recordList) throws IOException {
    	FileOutputStream fileOut = this.openFileOutput(fileName, this.MODE_PRIVATE);
    	//写入中文字符时会出现乱码
        BufferedWriter  bw= new BufferedWriter(new OutputStreamWriter(fileOut));
    	for(String str:recordList){
    	/*	byte[] buffer = str.getBytes("UTF-8");
    		fileOut.write("\r\n");
    		fileOut.write(buffer);*/
    		bw.write(str);
    		bw.newLine();
    	}
    	bw.close();
    	fileOut.close();
    }
    
    public List<String> readRecordFromFile(String fileName) throws IOException{
    	
    	List<String> recordList = new ArrayList<String>();
    	FileInputStream fileInput = this.openFileInput(fileName);
    	
    	BufferedReader br = new BufferedReader(new InputStreamReader(fileInput));
    	String str = null;
    	while ((str = br.readLine()) != null) {
    		recordList.add(str);
    	}
    	br.close();
    	fileInput.close();
    	return recordList;
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (((keyCode == KeyEvent.KEYCODE_BACK) ||(keyCode == KeyEvent.KEYCODE_HOME))&& event.getRepeatCount() == 0) {
        	dialog(this);
        }
        return false;
    }    
    
    
    public void dialog(final CalculateActivity activity) {
    	AlertDialog.Builder builder = new Builder(activity);
    	builder.setMessage("确认退出吗？");
    	builder.setTitle("提示");
    	builder.setPositiveButton("确认", new OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			
    			try {
					activity.writeRecord2File(activity.fileName,activity.recordList);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			dialog.dismiss();
    			android.os.Process.killProcess(android.os.Process
                        .myPid());
    		}
    	});
    	builder.setNegativeButton("取消", new OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    		}
    	});
    	
    	builder.create().show();
	}
    
	public TextView getContentShow() {
		return contentShow;
	}

	public void setContentShow(TextView contentShow) {
		this.contentShow = contentShow;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}
